<template>
  <NuxtLayout class="hideScrollBar">
    <!-- h5 加载中的 lo ading -->
    <Loading v-if="isLoading && globalStore.$state.isiOS"></Loading>
    <NuxtPage v-else />
  </NuxtLayout>

  <!-- 全局的调试弹窗 -->
  <DebuggerPopup
    v-model:show="isShowDebuggerPopup"
    :text="debuggerInfo"
  ></DebuggerPopup>
</template>

<script setup lang="ts">
import { setToastDefaultOptions, showToast } from "vant";
import { useGlobalStore } from "~~/store/global";
import { useEventBus } from "@vueuse/core";
import { useLogStore } from "~~/store/modules/log";
import { errorkeyoperation } from "~~/api/log";
import DebuggerPopup from "./components/log/debuggerPopup.vue";
import { isAndroid, closeLoadingToast } from "@/utils";
import { queryAirdropConfig } from "@/api/airdrop";
import { usePageCacheStore } from "~~/store/modules/pageCache";
import { useLotteryMoneyStore } from "~~/store/modules/lottery-money";

const router = useRouter(); // 路由跳转
const { t } = useI18n();
const { WEB_NODE_ENV = "prod" } = useRuntimeConfig().public;
const globalStore = useGlobalStore();
const uselog = useLogStore();

const pageCache = usePageCacheStore();
const lotteryMoneyStore = useLotteryMoneyStore();

setToastDefaultOptions({ duration: 2500 });

const isLoading = ref(true);
const isShowDebuggerPopup = ref(false); // 调试弹窗
const debuggerInfo = ref(""); // 传递调试信息

// 通知: 方便某些无法使用useI18n的场景,http 请求中无法使用翻译
let showToastEmit: any = null;
let showLoadingEmit: any = null;
let showDebuggerEmit: any = null;

/**
 * @description: iphone X 底部安全区域适配
 */
const updateSafeAreaInsets = () => {
  if (process.client) {
    const safeAreaInsetBottom = getComputedStyle(
      document.documentElement
    ).getPropertyValue("env(safe-area-inset-bottom)");
    if (safeAreaInsetBottom) {
      document.documentElement.style.setProperty(
        "--safe-area-inset-bottom",
        safeAreaInsetBottom
      );
    } else {
      // 如果 env(safe-area-inset-bottom) 不可用，手动设置一个值
      let fallbackInsetBottom = globalStore.$state.IsIphoneX ? "34px" : "0px"; // 根据需要调整
      // 开发环境模拟 iphoneX 手机
      if (process.env.NODE_ENV == "development") {
        if (!isAndroid.value) {
          fallbackInsetBottom = "34px";
        }
      }
      // const fallbackInsetBottom = true ? "34px" : "0px"; // 根据需要调整
      document.documentElement.style.setProperty(
        "--safe-area-inset-bottom",
        fallbackInsetBottom
      );
    }
  }
};

// 入口权限
const getConfigRequest = () => {
  const pages = [
    // "index",
    "coin-coin",
    "FAQ-question",
    "dividends-dividends",
    "recycling-recycling",
    "plan-plan",
    "wallet-wallet",
    "invite-friends-share", // 抽美金邀请好友页面
  ];
  let isRequest = true;

  pages.forEach((e) => {
    if (
      router.currentRoute.value.name &&
      (router.currentRoute.value.name as string).startsWith(e)
    ) {
      isRequest = false;
    }
  });
  if (!isRequest) return;
  queryAirdropConfig().then((res) => {
    if (res) {
      console.log("活动入口-权限:", res);
      // 1. 保存数据,给活动页面使用
      pageCache.addPageData("activity-Config-info", res, 20 * 60 * 1000);
      // 2. 邀请好友入口,权限
      lotteryMoneyStore.$patch((state) => {
        state.isShowInviteLottery = !!res.inviteCode && res.accountType == 0;
        state.inviteLotteryCode = res.inviteCode || ""; // 邀请码
      });
    }
  });
};

onMounted(async () => {
  // 1. 取消 loading 展示
  isLoading.value = false;
  // 1.1 获取入口权限
  getConfigRequest();
  console.warn("当前环境：", WEB_NODE_ENV);
  // 2.1 注册toast提醒（方便某些无法使用useI18n的场景）
  showToastEmit = useEventBus("showToast-emit");
  showToastEmit.on((val: any) => {
    if (val && val.includes(".")) {
      showToast({
        message: t(val),
        forbidClick: true,
      });
    } else {
      showToast({
        message: val,
        forbidClick: true,
      });
    }
  });
  // 2.2 关闭全局的 loading
  showLoadingEmit = useEventBus("showLoading-emit");
  showLoadingEmit.on(() => {
    closeLoadingToast();
  });
  // 2.3 全局的调试框
  showDebuggerEmit = useEventBus("show-debugger-emit");
  showDebuggerEmit.on((val: any) => {
    if (WEB_NODE_ENV == "prod") return;
    debuggerInfo.value = val;
    isShowDebuggerPopup.value = true;
  });
  // 3. 获取服务器上需要额外过滤的errors信息
  errorkeyoperation().then((res: any) => {
    uselog.$patch((state) => {
      state.ignoreDynamics = res;
    });
  });
  // 4. 注册iOS 的桥接函数
  (bridge as any).exportFn();
  // 5. iphone X 底部安全区域适配
  updateSafeAreaInsets();
});

onBeforeUnmount(() => {
  showLoadingEmit && showLoadingEmit.reset();
  showDebuggerEmit && showDebuggerEmit.reset();
  showToastEmit && showToastEmit.reset();
  // window.removeEventListener("resize", updateSafeAreaInsets);
});

/**
 * @description: 网站配置
 */
useSeoMeta({
  title: "BDC",
  description: "BDC",
  ogTitle: "Dana BDC",
  ogDescription: "Dana BDC.",
  ogImage: "https://bdc.btcdana.org/fx/image/mvp/balance-bdc.png",
  ogUrl: "https://bdc.btcdana.org/fx/tabbar?idx=0",
  twitterTitle: "BDC",
  twitterDescription: "BDC",
  twitterImage: "https://bdc.btcdana.org/fx/image/mvp/balance-bdc.png",
  twitterCard: "summary",
});

useHead({
  htmlAttrs: {
    lang: "en",
  },
  link: [
    {
      rel: "icon",
      type: "image/png",
      href: "https://bdc.btcdana.org/fx/image/mvp/balance-bdc.png",
    },
  ],
});
</script>
<style>
/* 官方推荐动画效果 */
.page-enter-active,
.page-leave-active {
   transition: all 0.4s;
}
.page-enter-from,
.page-leave-to {
   opacity: 0;
   filter: blur(1rem);
}
/* 隐藏导航栏 */
.hideScrollBar::-webkit-scrollbar {
  width: 0;
}

.hideScrollBar {
  -ms-overflow-style: none;
  overflow: -moz-scrollbars-none;
}
</style>
